package com.crud.generator.exception;

import com.crud.generator.common.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 * 
 * @author CRUD-Generator
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    
    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiResponse<Map<String, String>>> handleValidationException(
            MethodArgumentNotValidException ex, WebRequest request) {
        
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        
        log.warn("参数验证失败: {}", errors);
        
        ApiResponse<Map<String, String>> response = ApiResponse.error(400, "参数验证失败");
        response.setData(errors);
        response.setPath(request.getDescription(false));
        
        return ResponseEntity.badRequest().body(response);
    }
    
    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<ApiResponse<Map<String, String>>> handleBindException(
            BindException ex, WebRequest request) {
        
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        
        log.warn("数据绑定失败: {}", errors);
        
        ApiResponse<Map<String, String>> response = ApiResponse.error(400, "数据绑定失败");
        response.setData(errors);
        response.setPath(request.getDescription(false));
        
        return ResponseEntity.badRequest().body(response);
    }
    
    /**
     * 处理约束违反异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<ApiResponse<String>> handleConstraintViolationException(
            ConstraintViolationException ex, WebRequest request) {
        
        log.warn("约束验证失败: {}", ex.getMessage());
        
        ApiResponse<String> response = ApiResponse.error(400, "约束验证失败: " + ex.getMessage());
        response.setPath(request.getDescription(false));
        
        return ResponseEntity.badRequest().body(response);
    }
    
    /**
     * 处理SQL解析异常
     */
    @ExceptionHandler(SqlParseException.class)
    public ResponseEntity<ApiResponse<String>> handleSqlParseException(
            SqlParseException ex, WebRequest request) {
        
        log.warn("SQL解析失败: {}", ex.getMessage());
        
        ApiResponse<String> response = ApiResponse.error(400, "SQL解析失败: " + ex.getMessage());
        response.setPath(request.getDescription(false));
        
        return ResponseEntity.badRequest().body(response);
    }
    
    /**
     * 处理代码生成异常
     */
    @ExceptionHandler(CodeGenerationException.class)
    public ResponseEntity<ApiResponse<String>> handleCodeGenerationException(
            CodeGenerationException ex, WebRequest request) {
        
        log.error("代码生成失败: {}", ex.getMessage(), ex);
        
        ApiResponse<String> response = ApiResponse.error(500, "代码生成失败: " + ex.getMessage());
        response.setPath(request.getDescription(false));
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }
    
    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ApiResponse<String>> handleIllegalArgumentException(
            IllegalArgumentException ex, WebRequest request) {
        
        log.warn("非法参数: {}", ex.getMessage());
        
        ApiResponse<String> response = ApiResponse.error(400, "参数错误: " + ex.getMessage());
        response.setPath(request.getDescription(false));
        
        return ResponseEntity.badRequest().body(response);
    }
    
    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<ApiResponse<String>> handleRuntimeException(
            RuntimeException ex, WebRequest request) {
        
        log.error("运行时异常: {}", ex.getMessage(), ex);
        
        ApiResponse<String> response = ApiResponse.serverError("系统内部错误，请稍后重试");
        response.setPath(request.getDescription(false));
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }
    
    /**
     * 处理通用异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<String>> handleGenericException(
            Exception ex, WebRequest request) {
        
        log.error("未知异常: {}", ex.getMessage(), ex);
        
        ApiResponse<String> response = ApiResponse.serverError("系统发生未知错误，请联系管理员");
        response.setPath(request.getDescription(false));
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }
}
